package com.sie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sie.entity.Authority;
import com.sie.mapper.AuthorityMapper;
import com.sie.service.AuthorityService;
import com.sie.util.AsdUtils;
import com.sie.util.ReslUtil;
import com.sie.util.RoleAuthorityFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 权限服务实现类
 */
@Service
@Transactional
@SuppressWarnings("all")
public class AuthorityServiceImpl implements AuthorityService {
    @Autowired
    private AuthorityMapper authorityMapper;

    /**
     * 根据lv查询所有上级权限
     */
    @Override
    public Map findParentAuthority(String lv) {
//        非空判断
        if (lv == null)
            return ReslUtil.fail();
//        只有lv2和lv3才拥有父权限
        if ("2".equals(lv) || "3".equals(lv)) {
            Map success = ReslUtil.success();
//            将获取到的权限序列化并存进data，返回给前端
            success.put("data", RoleAuthorityFormatUtils.authorityFormat(authorityMapper.findAuthorityByLv((Integer.parseInt(lv) - 1) + "")));
            return success;
        }
        return ReslUtil.fail();

    }

    /**
     * 分页条件查询
     *
     * @param authority
     * @param pageNum
     * @param pageSize
     * @param request
     * @return
     */
    @Override
    public Map findByPage(Authority authority, String pageNum, String pageSize, HttpServletRequest request) {
        if (!AsdUtils.asd(request, "查询权限")) {
            return ReslUtil.fail();
        }
//        给分页参数设置默认值
        if ("".equals(pageNum) || pageNum == null)
            pageNum = "1";
        if ("".equals(pageSize) || pageSize == null)
            pageSize = "5";
//      分页操作
        PageHelper.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        List<Authority> authorities = RoleAuthorityFormatUtils.authorityFormat(authorityMapper.findByPage(authority));
        PageInfo<Authority> authorityPageInfo = new PageInfo<>(authorities);
//      封装返回信息
        Map success = ReslUtil.success();
        success.put("data", authorityPageInfo.getList());
        success.put("total", authorityPageInfo.getTotal());
        success.put("size", authorityPageInfo.getPageSize());
        return success;
    }

    /**
     * 查询所有权限信息(给设置权限做铺垫)
     *
     * @param request
     * @return
     */
    @Override
    public Map findAll(HttpServletRequest request) {
        if (!AsdUtils.asd(request, "查询权限")) {
            return ReslUtil.fail();
        }
//      查询所有权限
        List<Authority> authorities = RoleAuthorityFormatUtils.authorityFormat(authorityMapper.selectList(new QueryWrapper<>()));
//      封装返回信息
        Map success = ReslUtil.success();
        success.put("data", authorities);
        return success;
    }

    //    根据id删除权限
    @Override
    public Map deleteById(String id, HttpServletRequest request) {
//        判断是否拥有权限或者是否属于无法删除权限
        if (!AsdUtils.asd(request, "删除权限") || id == null || Integer.parseInt(id) <= 16) {
            return ReslUtil.fail();
        }
//        产出与改权限相关的表信息
        Integer integer = authorityMapper.deleteAuthorityById(id);
        int i = authorityMapper.deleteAuthorityAndRole(id);
        if (integer == 1) {
            return ReslUtil.success();
        }
        return ReslUtil.fail();
    }

    /**
     * 根据id批量删除
     *
     * @param list
     * @param request
     * @return
     */
    @Override
    public Map deleteList(List<String> list, HttpServletRequest request) {
        if (!AsdUtils.asd(request, "删除权限")) {
            return ReslUtil.fail();
        }
        //声明一个flag信号
        boolean flag = false;
//        遍历id数组进行处理
        for (String e : list) {
//            排除id小于16的权限,若有一条被删除则属于成功删除
            if (Integer.parseInt(e) > 16) {
                flag = true;
                authorityMapper.deleteAuthorityById(e + "");
                authorityMapper.deleteAuthorityAndRole(e + "");
            }
        }
        if (flag)
            return ReslUtil.success();
        return ReslUtil.fail();
    }

    /**
     * 新增权限
     *
     * @param authority
     * @param request
     * @return
     */
    @Override
    public Map addAuthority(Authority authority, HttpServletRequest request) {
        if (!AsdUtils.asd(request, "新增权限")) {
            return ReslUtil.fail();
        }
//        判断是否存在父级权限,若不存在则设置为0
        if (authority.getAuthParentId() == null || authority.getAuthParentId().equals(""))
            authority.setAuthParentId("0");
//        拼接权限名规范
        authority.setAuthName("AUTH_" + authority.getAuthName());
//        查询同父级权限下的子权限数量
        List<Authority> brother = authorityMapper.FindFather(authority.getAuthParentId());
//        生成对应序号
        authority.setAuthNo(String.valueOf(brother.size()));
//        插入操作
        int insert = authorityMapper.insert(authority);
        int i = authorityMapper.setAuthority("1", authority.getAuthId());
        if (insert == 1 && i == 1)
            return ReslUtil.success();
        return ReslUtil.fail();
    }

    /**
     * 修改权限
     *
     * @param authority
     * @param request
     * @return
     */
    @Override
    public Map update(Authority authority, HttpServletRequest request) {
//        权限判定
        if (!AsdUtils.asd(request, "修改权限")) {
            return ReslUtil.fail();
        }
//        格式化权限名
        authority.setAuthName("AUTH_" + authority.getAuthName());
//        执行sql
        int update = authorityMapper.updateAuthority(authority);
//        判断结果
        if (update == 1)
            return ReslUtil.success();
        return ReslUtil.fail();
    }

    /**
     * 权限名查重
     *
     * @param name
     * @return
     */
    @Override
    public Map findByName(String name) {
//        非空判断
        if (name == null || name.equals(""))
            return ReslUtil.fail();
//        根据权限名查找,若不存在,则用户名可使用
        Authority byName = authorityMapper.findByName("AUTH_" + name);
        if (byName == null)
            return ReslUtil.success();
        return ReslUtil.fail();
    }

    /**
     * 根据id查寻权限
     *
     * @param roleId
     * @return
     */
    @Override
    public List<Authority> findAuthByRoleId(String roleId) {
        return authorityMapper.findAuthByRoleId(roleId);
    }

    /**
     * 给角色赋予权限
     *
     * @param id
     * @param list
     * @param request
     * @return
     */
    @Override
    public Map setAuthority(String id, List<String> list, HttpServletRequest request) {
//        验证权限
        if (!AsdUtils.asd(request, "修改角色")) {
            return ReslUtil.fail();
        }
//        清空现存权限
        authorityMapper.deleteAllAuthByRoleId(id);
//        若为空.则不赋予任何权限
        if (list == null) {
            return ReslUtil.fail();
        }
//        去重处理
        HashSet<String> fids = new HashSet<>();
        list.forEach(auth -> {
            fids.add(auth);
            Authority byId = authorityMapper.findById(auth);
            if (byId.getAuthLv().equals("2")) {
                fids.add(byId.getAuthParentId());
            } else if (byId.getAuthLv().equals("3")) {
                fids.add(byId.getAuthParentId());
                fids.add(authorityMapper.findById(byId.getAuthParentId()).getAuthParentId());
            }
        });
//        获取所有权限
        fids.forEach(authId -> {
            authorityMapper.setAuthority(id, authId);
        });
        return ReslUtil.success();
    }


}
